package com.hbnu.mysql.Cart;

import com.hbnu.mysql.Flower.FlowerDAO;
import com.hbnu.mysql.User.LRService;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/*
 * @author zouting
 * @Date 2025-11-25-17:08
 *
 */public class CartService {
     private final String loginUser;
     private final Scanner scanner;
     private final FlowerDAO flowerDAO;

     public CartService(String loginUser) {
         this.loginUser = loginUser;
         this.scanner = new Scanner(System.in);
         this.flowerDAO = new FlowerDAO();
     }

     // 查看购物车
    public void viewCart() {
        String sql = "SELECT c.cid, c.fid, f.fname, f.price, c.quantity, " +
                "(f.price * c.quantity) as total " +
                "FROM tb_cart c " +
                "JOIN tb_flower f ON c.fid = f.fid " +
                "WHERE c.username = ?";
        try(
            Connection connection = LRService.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(sql)
        ){
            preparedStatement.setString(1, loginUser);
            ResultSet resultSet = preparedStatement.executeQuery();

                System.out.println("\n========== 我的购物车 ==========");
                System.out.printf("%-8s %-12s %-15s %-10s %-8s %-10s\n",
                        "购物车ID", "鲜花编号", "鲜花名称", "单价", "数量", "小计");
                System.out.println("------------------------------------------------------------");
                double grandTotal = 0.0;
                boolean hasItems = false;
                // 修改 viewCart 方法中的 while 循环部分
                while (resultSet.next()) {
                    try {
                        hasItems = true;
                        String cid = resultSet.getString("cid");
                        String fid = resultSet.getString("fid");
                        String fname = resultSet.getString("fname");
                        double price = resultSet.getDouble("price");
                        int quantity = resultSet.getInt("quantity");
                        double total = resultSet.getDouble("total"); // 注意此处原代码有误，应为字符串"total"
                        grandTotal += total;
                        System.out.printf("%-8s %-12s %-15s %-10.2f %-8d %-10.2f\n",
                                cid, fid, fname, price, quantity, total);
                    } catch (SQLException e) {
                        System.out.println("读取购物车数据时发生错误: " + e.getMessage());
                    }
                }


                if (!hasItems) {
                    System.out.println("购物车为空");
                } else {
                    System.out.println("------------------------------------------------------------");
                    System.out.printf("总金额: ￥%.2f\n", grandTotal);
                }

            } catch (Exception e) {
                System.out.println("查看购物车失败: " + e.getMessage());
            }
        }

    // 更新数量
    public void updateCartItem() {
        viewCart();
        System.out.print("请输入要修改的购物车ID: ");
        String cid = scanner.nextLine().trim();
        System.out.print("请输入新的数量(输入0删除商品): ");
        int newQuantity;

        try {
            newQuantity = Integer.parseInt(scanner.nextLine().trim());
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字");
            return;
        }

        if (newQuantity == 0) {
            // 删除商品
            deleteCartItem(cid);
            return;
        }

        String sql = "UPDATE tb_cart SET quantity = ? WHERE cid = ? AND username = ?";

        try (Connection conn = LRService.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setInt(1, newQuantity);
            ps.setString(2, cid);
            ps.setString(3, loginUser);

            int rowsAffected = ps.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("修改成功");
            } else {
                System.out.println("修改失败，请检查购物车ID是否正确");
            }

        } catch (Exception e) {
            System.out.println("修改购物车失败: " + e.getMessage());
        }
    }


    // 删除商品
    public void deleteCartItem(String cid) {

        String sql = "DELETE FROM tb_cart WHERE cid = ? AND username = ?";
        try (Connection conn = LRService.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setString(1, cid);
            ps.setString(2, loginUser);

            int rowsAffected = ps.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("删除成功");
            } else {
                System.out.println("删除失败，请检查购物车ID是否正确");
            }

        } catch (Exception e) {
            System.out.println("删除购物车商品失败: " + e.getMessage());
        }
    }

    /*
    * 清空购物车*/
    public void clearCart() {
        System.out.print("确定要清空购物车吗？(y/n): ");
        String confirm = scanner.nextLine().trim();

        if (!"y".equalsIgnoreCase(confirm)) {
            System.out.println("取消清空操作");
            return;
        }

        String sql = "DELETE FROM tb_cart WHERE username = ?";

        try (Connection conn = LRService.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setString(1, loginUser);
            int rowsAffected = ps.executeUpdate();
            System.out.println("已清空 " + rowsAffected + " 件商品");

        } catch (Exception e) {
            System.out.println("清空购物车失败: " + e.getMessage());
        }
    }


    // 结算
    public void checkout() {
        viewCart();
        String sql = "SELECT SUM(f.price * c.quantity) AS total " +
                "FROM tb_cart c " +
                "JOIN tb_flower f ON c.fid = f.fid " +
                "WHERE c.username = ?";

        try(Connection connection = LRService.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(sql)
        ){
            preparedStatement.setString(1, loginUser);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                double total = resultSet.getDouble("total");
                if (total == 0){
                    System.out.println("购物车为空，请添加商品后再结算");
                    return;
                }
                OrderService orderService = new OrderService(loginUser);
                orderService.createOrder();
            }else{
                System.out.println("结算失败，请检查用户名是否正确");
            }
        }catch (Exception e){
            System.out.println("结算失败: " + e.getMessage());
        }
     }
}
